﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Ones.Infrastructure.Utils.Pagination.Impl
{
    [DataContract]
    public class CustomPagination<T> : IPagination<T> where T : class
    {
        #region Member Variables
        
        private readonly IList<T> _dataSource;
        
        #endregion
        
        #region Constructor
        
        public CustomPagination(IEnumerable<T> dataSource, int pageNumber, int pageSize, int totalItems)
        {
            _dataSource = dataSource.ToList();
            PageNumber = pageNumber;
            PageSize = pageSize;
            TotalItems = totalItems;
        }
        
        #endregion
        
        #region Getter/Setter
        
        [DataMember]
        public int PageSize { get; private set; }
        
        [DataMember]
        public int PageNumber { get; private set; }
        
        [DataMember]
        public int TotalItems { get; private set; }
        
        [DataMember]
        public int TotalPages
        {
            get
            {
                return (int)Math.Ceiling(((double)TotalItems) / PageSize);
            }
            private set
            {
            }
        }
        
        [DataMember]
        public int FirstItem
        {
            get
            {
                return ((PageNumber - 1) * PageSize) + 1;
            }
            private set
            {
            }
        }
        
        [DataMember]
        public int LastItem
        {
            get
            {
                return FirstItem + _dataSource.Count - 1;
            }
            private set
            {
            }
        }
        
        [DataMember]
        public bool HasPreviousPage
        {
            get
            {
                return PageNumber > 1;
            }
            private set
            {
            }
        }
        
        [DataMember]
        public bool HasNextPage
        {
            get
            {
                return PageNumber < TotalPages;
            }
            private set
            {
            }
        }
        
        #endregion
        
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _dataSource.GetEnumerator();
        }
        
        public IEnumerator<T> GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}